// Login/Login.js
var MCAP = require("../../utils/mcaptcha.js")
var websocket = require('../../utils/websocket.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    idcode: "../../images/yzm.png",
    /*验证码的图片*/
    kaptch: "",
    username: "",
    password: "",
    yzm: "",
    aodeStr: ''


  },

  /**
   * 生命周期函数--监听页面加载
   */

  setUserName: function(e) {
    this.data.username = e.detail.value;
  },
  setPassword: function(e) {
    this.data.password = e.detail.value;
  },
  setCode: function(e) {
    this.data.yzm = e.detail.value;
  },
  clicks: function(options) {
    // /** 333333333333333333*/
    // var that=this;

    // console.log("click");
    // var api = "http://47.103.21.65:5645/user/getKaptche";
    // // that.setData({
    // //   idcode: api

    // // })
    // wx.request({
    //   url: api,
    //   method:"GET",
    //   responseType: 'arraybuffer',//接受
    //   data: {  //参数传递

    //   },
    //   header: { //设置请求头
    //     'content-type': 'application/json' // 默认值//header:{...}用啥设置啥，
    //   },

    //   success: function (res) {
    //     //---------------------------
    //     let base64 = wx.arrayBufferToBase64(res.data);
    //     console.log(res.header.token);//验证码的神秘代码
    //     console.log("d");
    //     that.setData({
    //       kaptch:res.header.token,
    //       idcode: 'data:image/jpg;base64,' + base64
    //     })
    //   },
    //   fail: function (error) { //请求失败
    //     console.log(error);
    //   }
    // })
    this.inirDraw();


  },
  login: function(options) { //登录请求
    var that = this;
    var api = "http://47.103.21.65:5645/user/login";

    if (that.data.username == "") {
      wx.showToast({
        title: '账号不能为空',
        icon: 'none',
        duration: 2000
      })

    } else if (that.data.password == "") {
      wx.showToast({
        title: '请输入密码',
        icon: 'none',
        duration: 2000
      })
    } else if (that.data.yzm == "") {
      wx.showToast({
        title: '验证码不能为空',
        icon: 'none',
        duration: 2000
      })

    }else{
      console.log(!that.compare(this.data.yzm,this.data.codeStr)+"[[[[[[[[[[[[[[[[[[[[[[[[[[[")
      if (that.compare(this.data.codeStr,this.data.yzm)){

        wx.showToast({
          title: '验证码错误',
          icon: 'none',
          duration: 2000
        })
      } else {
        wx.request({
          url: api,
          method: "POST",

          data: { //参数传递

            account: that.data.username,
            password: that.data.password,


          },
          header: { //设置请求头
            'content-type': 'application/x-www-form-urlencoded', // 默认值//header:{...}用啥设置啥，

          },

          success: function(res) { //请求成功
            console.log(res.data);

            if (res.data.code == 1) { //登录成功操作
              wx.showToast({
                title: res.data.msg,
                duration: 2000
              })


              setTimeout(function() {
                wx.navigateBack({
                  delta: 1
                })
              }, 1000);
              wx.setStorageSync("token", res.data.data.token)
              that.talking();
              websocket.connect();

            }
            if (res.data.code == -1) { //登录失败
              wx.showToast({
                title: res.data.msg,
                icon: "none",
                duration: 2000
              })
            }
            //  if(res.data.code==0){//验证码错误
            //    wx.showToast({
            //      title: res.data.msg,
            //      icon: "none",

            //      duration: 2000
            //    })
            //  }


          },
          fail: function(error) { //请求失败
            console.log(error);
            console.log(that.data.username);
          }
        })
      }
    }
  },
  onLoad: function(options) {
    var that = this;
    that.inirDraw();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  inirDraw() { //画验证码
    var that = this;
    var codes = that.getRanNum();
    that.setData({
      codeStr: codes
    })
    new MCAP({
      el: 'canvas',
      width: 96,
      heignt: 33,
      code: codes
    });
  },
  getRanNum: function() { //生成随机数
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var pwd = '';
    for (var i = 0; i < 4; i++) {
      if (Math.random() < 48) {
        pwd += chars.charAt(Math.random() * 48 - 1);
      }
    }
    return pwd;
  },


  compare(one, two) { //one为验证码 two为输入的 大小写不区分
    var a = true;
    var onechar = new Array();
    var twochar = new Array();
    var a = one.toUpperCase();
    var b=two.toUpperCase();
    onechar = a.split("");
    twochar = b.split("");
    if (onechar.length != twochar.length) {
      a = true;
    } else {
     /**========================================================================= */
      console.log(onechar)
      for(var i=0;i<onechar.length;i++){
          if(onechar[i]!=twochar[i]){
            return a=true;
          }else{
            a=false
          
        }
      }

       }

      
    

    
    console.log(a)

    return a;
  },

  navigatRegister: function() { //跳转到注册界面
    wx.navigateTo({
      url: '../Register/Register',
    })
  },

  talking() {
    let token = wx.getStorageSync('token')
    wx.request({

      url: 'http://47.103.21.65:5645/product/login',
      method: 'GET',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'token': token
      },
      success: function(res) {
        console.log(res)
      },
      fail: function(res) {
        console.log(res)
      }
    })


  }



})